package com.vehiclesecure.util;

import com.vehiclesecure.model.User;
import com.vehiclesecure.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;
import java.util.Scanner;

/**
 * 密码重置工具
 * 用于帮助用户通过数据库中的密码哈希值找到对应的用户并重置密码
 */
@SpringBootApplication
@ComponentScan(basePackages = {"com.vehiclesecure"})
@EntityScan(basePackages = {"com.vehiclesecure.model"})
@EnableMongoRepositories(basePackages = {"com.vehiclesecure.repository"})
public class PasswordResetTool implements CommandLineRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public static void main(String[] args) {
        SpringApplication.run(PasswordResetTool.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("===== 车辆安全系统密码重置工具 ======");
        System.out.println("请输入数据库中的密码哈希值: ");
        String passwordHash = scanner.nextLine();
        
        // 查找使用该密码哈希值的用户
        List<User> allUsers = userRepository.findAll();
        User targetUser = null;
        
        for (User user : allUsers) {
            if (user.getPassword() != null && user.getPassword().equals(passwordHash)) {
                targetUser = user;
                break;
            }
        }
        
        if (targetUser == null) {
            System.out.println("未找到使用该密码哈希值的用户。");
            return;
        }
        
        System.out.println("找到用户：");
        System.out.println("ID: " + targetUser.getId());
        System.out.println("邮箱: " + targetUser.getEmail());
        System.out.println("姓名: " + targetUser.getFirstName() + " " + targetUser.getLastName());
        System.out.println("角色: " + targetUser.getRole());
        
        System.out.println("\n请输入新密码: ");
        String newPassword = scanner.nextLine();
        
        System.out.println("请再次输入新密码: ");
        String confirmPassword = scanner.nextLine();
        
        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致，请重试。");
            return;
        }
        
        // 更新密码
        targetUser.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(targetUser);
        
        System.out.println("\n密码重置成功！");
        System.out.println("用户邮箱: " + targetUser.getEmail());
        System.out.println("请使用新密码登录系统。");
        
        scanner.close();
    }
}